//
//  FlutterNativePlugin.m
//  Runner
//
//  Created by SamSam on 2021/9/10.
//

#import <Foundation/Foundation.h>
#import "FlutterNativePlugin.h"


@implementation FlutterNativePlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar{
    FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"gcglobal" binaryMessenger:[registrar messenger]];
    FlutterNativePlugin *instance = [[FlutterNativePlugin alloc]init];
    [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    if ([call.method isEqualToString:@"ShareWeb"]) {
        //接受fultter 传过来的参数
        NSLog(@"---%@",call.arguments);
        NSString *textToShare = call.arguments[@"title"];
            NSURL *urlShare = [NSURL URLWithString: call.arguments[@"link"]];
            UIImage* img= [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:call.arguments[@"image"]]]];
            NSArray *activityItems = @[textToShare, urlShare,img];
            UIActivityViewController *actVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
            actVC.view.backgroundColor = [UIColor whiteColor];
            //这儿一定要做iPhone与iPad的判断，因为这儿只有iPhone可以present，iPad需pop，所以这儿actVC.popoverPresentationController.sourceView = self.view;在iPad下必须有，不然iPad会crash，self.view你可以换成任何view，你可以理解为弹出的窗需要找个依托。
            if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
                actVC.popoverPresentationController.sourceView = [UIApplication sharedApplication].keyWindow;
                [[self currentViewController] presentViewController:actVC animated:YES completion:nil];
            } else {
                [[self currentViewController] presentViewController:actVC animated:YES completion:nil];
            }
      
    }else {
        result(FlutterMethodNotImplemented);
    }
}
- (UIViewController*)currentViewController{

UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
        while (1) {
            if ([vc isKindOfClass:[UITabBarController class]]) {
                vc = ((UITabBarController*)vc).selectedViewController;
                
            }
            if ([vc isKindOfClass:[UINavigationController class]]) {
                vc = ((UINavigationController*)vc).visibleViewController;
            }
            if (vc.presentedViewController) {
                vc = vc.presentedViewController;
            }else{
                break;
            }
            
        }
        return vc;
}

@end
